var EventProxy = require('eventproxy');
var entity = require('../entity');
var Relation = entity.Relation;
var redisManager = require('./redisManager');
var logger = require('../service/Logger');

exports.find2UsersRelation = function(userone, usertwo, callback){
    Relation.find({$or: [{userone: userone, usertwo: usertwo}, {userone:usertwo, usertwo: userone}]})
        .exec(function(err, rel){
        callback(err, rel)
    })
}

exports.findRelsByUserone = function(userone, pageNo, pageSize, callback){
    var start = (pageNo - 1)*pageSize;
    Relation.find({userone: userone})
        .sort({weight: 1})
        .skip(start)
        .limit(pageSize)
        .exec(function(err, rels){
            callback(err, rels);
        })
}

exports.findRelByUseroneAndTwo = function(userone, usertwo, callback){
    Relation.findOne({userone:userone, usertwo:usertwo})
        .exec(function(err, rel){
            callback(err, rel);
        })
}

exports.findRelAndAddTag = function(userone, usertwo, tag, callback){
    Relation.findOne({userone: userone, usertwo: usertwo})
        .exec(function(err, rel){
            if(err) return callback(err);
            if(rel){
                rel.tag.push(tag);
                rel.save(function(err, resp){
                    callback(err, resp);
                })
                callback(err, rel)
            }else{
                callback(err, null);
            }
        })
}

exports.findRelAndRemoveTag = function(userone, usertwo, tag, callback){
    Relation.findOne({userone: userone, usertwo: usertwo})
        .exec(function(err, rel){
            if(err) return callback(err);
            var tags = rel.tag;
            var tmp = [];
            for(var i= 0,len=tags.length; i<len; i++){
                if(tags[i] === tag){
                    continue
                }else{
                    tmp.push(tags[i]);
                }
            }
            rel.tag = tmp;
            rel.save(function(err, rel){
                callback(err, rel);
            });
            callback(err, rel);
        })
}

exports.addNewRelation = function(userone, usertwo, callback){
    _saveNewBothwayRels(userone, usertwo, function(err, resp){
        callback(err, resp);
    })
}
function _saveNewBothwayRels(userone, usertwo, weight, callback){
    var relation = new Relation();
    relation.userone = userone;
    relation.usertwo = usertwo;
    relation.weight = weight;
    relation.save(function(err, resp){
        if(err) return callback(err);
        var relationTwo = new Relation();
        relationTwo.userone = usertwo;
        relationTwo.usertwo = userone;
        relationTwo.weight = 1;
        relationTwo.save(function(err, resp){
            callback(err, resp);
        });
    });
}
exports.addRelationWeight = function(userone, usertwo, weight, callback){
    var _self = this;
    if(userone == usertwo){
        return callback(null, null);
    }
    //双向 加入朋友sortSet
    redisManager.addUserSet(userone, {id:usertwo}, function(err, resp){
        if(err) return callback(err);
        if(resp == 0){
            _self.subtractRelationWeight(userone, usertwo, weight, callback);
        }else{
            console.log('新建关系');
            redisManager.addBothUserSet(userone, usertwo, function(err, resp){
                if(err) return callback(err);
                _saveNewBothwayRels(userone, usertwo, weight, function(err, resp){
                    console.log('双向关系列表添加ok');
                    callback(err, resp)
                })
            }); //双向无序set
        }
    });// 无序set

}

exports.subtractRelationWeight = function(userone, usertwo, weight, callback){
    var ep = new EventProxy();
    ep.bind('error', function(err){
        return callback(err)
    });
    ep.all('useroneRel', 'usertwoRel', function(relone, reltwo){
        try{
            relone.weight = relone.weight + weight;
            relone.save(function(err, rel){
                if(err) return callback(err);
                reltwo.weight = reltwo.weight + weight;
                reltwo.save(function(err, reltwo){
                    callback(err, reltwo);
                });
            })
        }catch (err){
            logger.error('关系加权fail...');
            logger.error(err);
            callback(err);
        }
    });
    Relation.findOne({userone: userone, usertwo: usertwo}).exec(function(err, rel){
        if(err) ep.emit('error', err);
        ep.emit('useroneRel', rel);
    });
    Relation.findOne({userone: usertwo, usertwo: userone}).exec(function(err, rel){
        if(err) ep.emit('error', err);
        ep.emit('usertwoRel', rel);
    });
}

exports.addTag4Relation = function(userone, usertwo, tag, callback){
    Relation.find({userone: userone, usertwo: usertwo})
        .exec(function(err, rel){
            if(err) return callback(err)
            rel.tag.push(tag);
            rel.save(callback);
        })
}

/*exports.testChildRelation = function(userone, cb){
    var relation = new Relation();
    relation.userone = userone;
    relation.usertwo = 'user2';
    relation.weight = '456';
    relation.save(function(err, resp){
        if(err) return console.log(err);
            console.log(resp);
        cb()
    });
}*/